//
//  ForgotPasswordViewController.m
//  EastMarket
//
//  Created by 李鹏程 on 16/10/19.
//  Copyright © 2016年 guoguo. All rights reserved.
//

#import "ForgotPasswordViewController.h"

@interface ForgotPasswordViewController ()
{
    UIView *bgView;
    //UITextField *phone;
    UITextField *code;
    UINavigationBar *customNavigationBar;
    UIButton *yzButton;
}
@property(nonatomic, copy) NSString *oUserPhoneNum;
@property(assign, nonatomic) NSInteger timeCount;
@property(strong, nonatomic) NSTimer *timer;
//验证码
@property(copy, nonatomic) NSString *smsId;
@property (nonatomic, strong) UITextField *phone;
@property (nonatomic, strong) UITextField *psd;
@property (nonatomic, strong) UITextField *psdConfirm;
@end

@implementation ForgotPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"找回密码";
    self.view.backgroundColor = EastMarket_backgroundColor;
    [self createTextFields];

}

-(void)createTextFields
{
    CGFloat spacing = 8.0f;
    CGFloat border = 1.0f;
    
    bgView = [[UIView alloc]initWithFrame:CGRectMake(0, spacing, SCREEN_WIDTH, SCREEN_HEIGHT / 3)];
    bgView.layer.cornerRadius = 3.0;
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
    // 手机号
    UILabel *phonelabel = [[UILabel alloc]initWithFrame:CGRectMake(2 * spacing, 0, (bgView.frame.size.width - 5 * spacing) / 4, bgView.frame.size.height / 4)];
    phonelabel.text = @"手机号";
    phonelabel.textColor = [UIColor blackColor];
    phonelabel.textAlignment = NSTextAlignmentLeft;
    phonelabel.font = [UIFont systemFontOfSize:14];
    
    _phone = [self createTextFielfFrame:CGRectMake(phonelabel.frame.origin.x + phonelabel.frame.size.width + spacing, phonelabel.frame.origin.y, (bgView.frame.size.width - 6 * spacing) / 2, phonelabel.frame.size.height) font:[UIFont systemFontOfSize:14] placeholder:@"您的手机号"];
    _phone.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phone.keyboardType=UIKeyboardTypeNumberPad;
    
    yzButton = [[UIButton alloc]initWithFrame:CGRectMake(_phone.frame.origin.x + _phone.frame.size.width + 1, _phone.frame.origin.y, (bgView.frame.size.width - 6 * spacing) / 4 + spacing - 1, _phone.frame.size.height)];
    //yzButton.backgroundColor=[UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1];
    [yzButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    [yzButton setTitleColor:EastMarket_BlueColor forState:UIControlStateNormal];
    if (IPHONE4) {
        
        [yzButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
    } else {
        
        [yzButton.titleLabel setFont:[UIFont systemFontOfSize:13]];
    }
    [yzButton addTarget:self action:@selector(getValidCode:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:yzButton];

    
    UIImageView *line1 = [self createImageViewFrame:CGRectMake(phonelabel.frame.origin.x, phonelabel.frame.origin.y + phonelabel.frame.size.height - border, bgView.frame.size.width - 4 * spacing, border) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    // 验证码
    UILabel *codelabel = [[UILabel alloc]initWithFrame:CGRectMake(phonelabel.frame.origin.x, phonelabel.frame.origin.y + phonelabel.frame.size.height, (bgView.frame.size.width - 5 * spacing) / 4, phonelabel.frame.size.height)];
    codelabel.text = @"验证码";
    codelabel.textColor = [UIColor blackColor];
    codelabel.textAlignment = NSTextAlignmentLeft;
    codelabel.font = [UIFont systemFontOfSize:14];
    
    code = [self createTextFielfFrame:CGRectMake(_phone.frame.origin.x, codelabel.frame.origin.y, (bgView.frame.size.width - 6 * spacing) / 2, _phone.frame.size.height) font:[UIFont systemFontOfSize:14]  placeholder:@"您手机收到的验证码" ];
    code.clearButtonMode = UITextFieldViewModeWhileEditing;
    code.keyboardType=UIKeyboardTypeNumberPad;
    
    UIImageView *line2 = [self createImageViewFrame:CGRectMake(line1.frame.origin.x, codelabel.frame.origin.y + codelabel.frame.size.height - border, line1.frame.size.width, border) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    // 密码
    UILabel *psdlabel = [[UILabel alloc]initWithFrame:CGRectMake(codelabel.frame.origin.x, codelabel.frame.origin.y + codelabel.frame.size.height, codelabel.frame.size.width, codelabel.frame.size.height)];
    psdlabel.text = @"密 码";
    psdlabel.textColor = [UIColor blackColor];
    psdlabel.textAlignment = NSTextAlignmentLeft;
    psdlabel.font = [UIFont systemFontOfSize:14];
    
    _psd = [self createTextFielfFrame:CGRectMake(code.frame.origin.x, psdlabel.frame.origin.y, _phone.frame.size.width, code.frame.size.height) font:[UIFont systemFontOfSize:14]  placeholder:@"请输入您的新密码" ];
    _psd.clearButtonMode = UITextFieldViewModeWhileEditing;
    _psd.secureTextEntry = YES;
    
    UIImageView *line3 = [self createImageViewFrame:CGRectMake(line1.frame.origin.x, psdlabel.frame.origin.y + psdlabel.frame.size.height, line1.frame.size.width, border) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    // 确认密码
    UILabel *psdConfirmlabel = [[UILabel alloc]initWithFrame:CGRectMake(psdlabel.frame.origin.x, psdlabel.frame.origin.y + psdlabel.frame.size.height, psdlabel.frame.size.width, psdlabel.frame.size.height)];
    psdConfirmlabel.text = @"确认密码";
    psdConfirmlabel.textColor = [UIColor blackColor];
    psdConfirmlabel.textAlignment = NSTextAlignmentLeft;
    psdConfirmlabel.font = [UIFont systemFontOfSize:14];
    
    _psdConfirm = [self createTextFielfFrame:CGRectMake(_psd.frame.origin.x, psdConfirmlabel.frame.origin.y, _psd.frame.size.width, _psd.frame.size.height) font:[UIFont systemFontOfSize:14]  placeholder:@"请再次输入新密码" ];
    _psdConfirm.clearButtonMode = UITextFieldViewModeWhileEditing;
    _psdConfirm.secureTextEntry = YES;
    
    UIButton *landBtn = [self createButtonFrame:CGRectMake(2 * spacing, bgView.frame.size.height + bgView.frame.origin.y + 4 * spacing, SCREEN_WIDTH - 4 * spacing, 44) backImageName:nil title:@"提交" titleColor:[UIColor whiteColor]  font:[UIFont systemFontOfSize:17] target:self action:@selector(updateUserPas)];
    //landBtn.backgroundColor = [UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1];
    landBtn.backgroundColor = EastMarket_MainToneColor;
    landBtn.layer.cornerRadius = 5.0f;
    
    [bgView addSubview:phonelabel];
    [bgView addSubview:codelabel];
    [bgView addSubview:psdlabel];
    [bgView addSubview:psdConfirmlabel];
    
    [bgView addSubview:_phone];
    [bgView addSubview:code];
    [bgView addSubview:_psd];
    [bgView addSubview:_psdConfirm];
    
    [bgView addSubview:line1];
    [bgView addSubview:line2];
    [bgView addSubview:line3];
    [self.view addSubview:landBtn];
}

- (void)getValidCode:(UIButton *)sender
{
    if ([GlobalUnit isBlankString:_phone.text]) {
        
        [GlobalUnit showPopHint:@"请输入手机号" targetView:_phone showInView:self.view];
        return;
    } else if (![GlobalUnit isMobile:_phone.text]) {
        
        [GlobalUnit showPopHint:@"请输入正确的手机号" targetView:_phone showInView:self.view];
        return;
    }
    _oUserPhoneNum = _phone.text;
    sender.userInteractionEnabled = NO;
    self.timeCount = 60;
    //__weak ForgotPasswordViewController *weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reduceTime:) userInfo:sender repeats:YES];
//    [NSThread detachNewThreadSelector:@selector(callServerSendCode) toTarget:self withObject:nil];
}
/*
- (void)callServerSendCode {
    
    NSDictionary *dic = [AppWebServiceInterface SendMobileCheckCode:_phone.text type:@"3"];
    debugLog(@"%@", dic);
}
*/
- (void)reduceTime:(NSTimer *)codeTimer {
    self.timeCount--;
    if (self.timeCount == 0) {
        [yzButton setTitle:@"重新获取" forState:UIControlStateNormal];
        [yzButton setTitleColor:[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1] forState:UIControlStateNormal];
        UIButton *info = codeTimer.userInfo;
        info.enabled = YES;
        yzButton.userInteractionEnabled = YES;
        [self.timer invalidate];
    } else {
        NSString *str = [NSString stringWithFormat:@"重新获取(%lu)", self.timeCount];
        [yzButton setTitle:str forState:UIControlStateNormal];
        yzButton.userInteractionEnabled = NO;
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_phone resignFirstResponder];
}

-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField = [[UITextField alloc]initWithFrame:frame];
    
    textField.font = font;
    
    textField.textColor = [UIColor grayColor];
    
    textField.borderStyle = UITextBorderStyleNone;
    
    textField.placeholder = placeholder;
    
    return textField;
}

-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame];
    
    if (imageName)
    {
        imageView.image = [UIImage imageNamed:imageName];
    }
    if (color)
    {
        imageView.backgroundColor = color;
    }
    
    return imageView;
}

-(UIButton *)createButtonFrame:(CGRect)frame backImageName:(NSString *)imageName title:(NSString *)title titleColor:(UIColor *)color font:(UIFont *)font target:(id)target action:(SEL)action
{
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    if (imageName)
    {
        [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    
    if (font)
    {
        btn.titleLabel.font=font;
    }
    
    if (title)
    {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    if (color)
    {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
    if (target&&action)
    {
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}

// 更新用户密码
-(void)updateUserPas
{
    if ([GlobalUnit isBlankString:_phone.text]) {
        [GlobalUnit showPopHint:@"请输入手机号" targetView:_phone showInView:self.view];
        return;
    }
    if ([GlobalUnit isBlankString:code.text]) {
        [GlobalUnit showPopHint:@"请输入验证码" targetView:code showInView:self.view];
        return;
    }
    if ([GlobalUnit isBlankString:_psd.text]) {
        [GlobalUnit showPopHint:@"请输入新密码" targetView:_psd showInView:self.view];
        return;
    }
    if ([GlobalUnit isBlankString:_psdConfirm.text]) {
        [GlobalUnit showPopHint:@"请重新输入密码" targetView:_psdConfirm showInView:self.view];
        return;
    }
    
    if (![_psd.text isEqualToString:_psdConfirm.text]) {
        [GlobalUnit showPopHint:@"两次输入密码不一样" targetView:_psdConfirm showInView:self.view];
        return;
    }
    [SVProgressHUD showWithStatus:@"加载中"];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:EastMarket_MainToneColor];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];

    
    //    NewPassWordViewController *new = [[NewPassWordViewController alloc]init];
    //    //赋值
    //    new.userPhone = _phone.text;
    
    [NSThread detachNewThreadSelector:@selector(callSeverForgetPassword) toTarget:self withObject:nil];
}


-(void)callSeverForgetPassword {
    
    NSDictionary *dic = [AppServiceInterface ForgetPassword:_phone.text password:_psd.text mobileCheckCode:code.text];
    [self performSelectorOnMainThread:@selector(updateUI:) withObject:dic waitUntilDone:false];
}

- (void)updateUI:(NSDictionary *)dic {
    
    [SVProgressHUD dismiss];
    debugLog(@"%@", [dic objectForKey:@"success"]);
    if ([[dic objectForKey:@"success"] integerValue] == 1) {
        
        NSNotification *notice = [NSNotification notificationWithName:NotificationLoginSccess object:nil];
        [[NSNotificationCenter defaultCenter] postNotification:notice];
        [self.navigationController popToRootViewControllerAnimated:true];
    } else if(dic && [[dic objectForKey:@"success"] integerValue] != 1){
        
        [GlobalUnit showAlertHint:@"温馨提示" message:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
    } else {
    
         [GlobalUnit showAlertHint:@"温馨提示" message:@"请求服务器失败，请稍后重试"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
